package client;


import java.net.ConnectException;
import java.net.UnknownHostException;
import java.util.Properties;

import javax.jms.QueueConnectionFactory;
import javax.jms.TopicConnectionFactory;
import javax.naming.Context;
import javax.naming.InitialContext;

import org.objectweb.joram.client.jms.Queue;
import org.objectweb.joram.client.jms.Topic;
import org.objectweb.joram.client.jms.admin.AdminException;
import org.objectweb.joram.client.jms.admin.AdminModule;
import org.objectweb.joram.client.jms.admin.User;
import org.objectweb.joram.client.jms.tcp.QueueTcpConnectionFactory;
import org.objectweb.joram.client.jms.tcp.TopicTcpConnectionFactory;

public class Amministratore {

	private String server=null;
	private Context ictx = null;
	private Properties env = null;
	
	public Amministratore(String serverJoram){
		server = serverJoram;
		env = new Properties();
		env.put("java.naming.factory.initial",
		"fr.dyade.aaa.jndi2.client.NamingContextFactory");
		env.put("java.naming.factory.host", server);
		env.put("java.naming.factory.port", "16400");

		
		try {
			ictx = new InitialContext(env);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public void createTopic(String federazione){
		try {
			AdminModule.connect(server, 16010, "root", "root", 20);
			Topic topic = (Topic) Topic.create(federazione);
			topic.setFreeReading();
			topic.setFreeWriting();
			User user = User.create("anonymous", "anonymous");
			TopicConnectionFactory tcf = TopicTcpConnectionFactory.create(
					server, 16010);

			ictx.rebind(federazione, topic);
			ictx.rebind(federazione + "tcf", tcf);
			AdminModule.disconnect();

		} catch (Exception e) {
			e.printStackTrace();
		}		
	}
	
	
	public Queue createQueue(String cliID){
		Queue queue = null;
		try {
			AdminModule.connect(server, 16010, "root", "root", 20);
			queue = (Queue) Queue.create(cliID);
			queue.setFreeReading();
			queue.setFreeWriting();
			QueueConnectionFactory qcf = QueueTcpConnectionFactory.create(
					server, 16010);

			ictx.rebind(cliID, queue);
			ictx.rebind(cliID + "qcf", qcf);
			AdminModule.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return queue;
	}

	public int getSubscriptionsOnTopic(Topic topic) {
		int num = 0;
		try{
			AdminModule.connect(server, 16010, "root", "root", 20);
			num = topic.getSubscriptions();
			AdminModule.disconnect();
		} catch (Exception e){
			e.printStackTrace();
		}
		return num;
	}

	public void clearQueue(Queue myQueue) {
		try {
			AdminModule.connect(server, 16010, "root", "root", 20);
			myQueue.clear();
			AdminModule.disconnect();
		} catch (UnknownHostException e) {
			System.err.println("Problemi con Admin Module");
		} catch (ConnectException e) {
			e.printStackTrace();
		} catch (AdminException e) {
			e.printStackTrace();
		}
		
	}
	
}
